package example.org.aspectj.lang.annotation.before;

import java.util.Arrays;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;

import com.mongodb.DBObject;

@Aspect
public class MongoTemplateAspect {
	private Log log = LogFactory.getLog(getClass());
	
	/* 环绕通知 */
	@Around("execution(* org.springframework.data.mongodb.core.MongoTemplate.find*(..))")
	public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable{
		log.info("THe method " + joinPoint.getSignature().getName() + "() begins with " + Arrays.toString(joinPoint.getArgs()));
		try {
			Object[] objs = joinPoint.getArgs();
			if(objs != null && objs.length > 1){
				for(Object obj: objs){
					if(obj instanceof Query){
						if(obj instanceof BasicQuery){
							BasicQuery basicQuery = (BasicQuery)obj;
							DBObject dbObject = basicQuery.getQueryObject();
							
							System.out.println(dbObject.keySet());
							
							@SuppressWarnings("rawtypes")
							Map map = dbObject.toMap();
							System.out.println(map);
						}
					}
				}
			}
			
			Object result = joinPoint.proceed();
			log.info("The method " + joinPoint.getSignature().getName() + "() ends with " + result);
			return result;
		} catch (IllegalArgumentException e) {
			log.error("Illegal argument " + Arrays.toString(joinPoint.getArgs()) + " in " + joinPoint.getSignature().getName() + "()");
			throw e;
		}
	}
}
